package edu.friday.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import edu.friday.common.constant.Constants;
import edu.friday.common.constant.UserConstants;
import edu.friday.common.result.Pageable;
import edu.friday.common.result.TableDataInfo;
import edu.friday.mapper.SysRoleMapper;
import edu.friday.mapper.SysUserMapper;
import edu.friday.model.SysUser;
import edu.friday.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper roleMapper;

    @Override
    public TableDataInfo selectUserList(SysUser sysUser, Pageable page) {
        Page<SysUser> pages = PageHelper.startPage(page.getPage(),page.getSize());
        //执行查询会自动加上分页语句
        List<SysUser> userList=sysUserMapper.selectAll(sysUser);
        TableDataInfo t=TableDataInfo.success(userList,pages.getTotal());
        return t;
    }

    @Override
    public int deleteUserByIds(Long[] userIds) {
        return sysUserMapper.deleteByIds(userIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser sysUser) {
        //插入角色用户关系表
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("userId",sysUser.getUserId());
        map.put("roleIds",sysUser.getRoleIds());
        roleMapper.insertUserRole(map);

        sysUser.setCreateBy("admin");
        sysUser.setCreateTime(new Date());
        sysUser.setStatus(UserConstants.NORMAL);
        sysUser.setDelFlag(Constants.DEL_NOT_FLAG);
        return sysUserMapper.insertSelective(sysUser);
    }

    @Override
    public boolean checkUserNameUnique(String userName) {
        return sysUserMapper.checkUserNameUnique(userName)>0?false:true;
    }

    @Override
    public int updateUser(SysUser user) {
        return sysUserMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public SysUser selectUserById(Long userId) {
        return sysUserMapper.selectByPrimaryKey(userId);
    }

    @Override
    public SysUser selectUserByUserName(String username) {
        return sysUserMapper.selectUserByUserName(username);
    }
}
